import { constantRoutes } from '../constantRoutes'
import { menuFieldInvert, dataToRouteMenu, routerToTree, treeToAscending, removeEmptyCatalog, resetRedirect } from './public'
import { cloneDeep } from 'lodash-es'

// 导出静态路由作为菜单数据使用
export const getConstantMenu = (permitList) => {
  const result = []
  if (constantRoutes.length > 0) {
    if (permitList && permitList.length > 0) {
      cloneDeep(constantRoutes).forEach((item) => {
        if (!item.permit) {
          result.push(item)
        } else {
          const index = permitList.findIndex((v) => v === item.permit)
          if (index >= 0) {
            result.push(item)
          }
        }
      })
    } else {
      cloneDeep(constantRoutes).forEach((item) => {
        if (!item.permit) {
          result.push(item)
        }
      })
    }
  }
  return result
}

// 后端接口获取到的数据转化为菜单
export const asyncPermitMenu = (routeList, permitList) => {
  const result = getConstantMenu(permitList)
  const arr = []
  if (routeList && routeList.length > 0) {
    let routerArr = []
    if (result.length > 0) {
      routerArr = cloneDeep(menuFieldInvert(routeList)).concat(...result)
    } else {
      routerArr = cloneDeep(menuFieldInvert(routeList))
    }
    routerArr.forEach((item) => {
      const itemRoute = dataToRouteMenu(item, false)
      arr.push(itemRoute)
    })
  } else {
    result.forEach((item) => {
      const itemRoute = dataToRouteMenu(item, false)
      arr.push(itemRoute)
    })
  }
  if (arr.length > 0) {
    const treeRoutes = routerToTree(arr)
    // 删除无子级菜单层路由的目录层菜单，这种目录层菜单不应该被显示
    removeEmptyCatalog(treeRoutes)
    // 重置各目录层的重定向
    resetRedirect(treeRoutes)
    // 数据排序
    treeToAscending(treeRoutes)
    return filterMenuTree(treeRoutes)
  } else {
    return []
  }
}

// 过滤meta中showLink为false的路由
export const filterMenuTree = (data: any) => {
  const newTree = data.filter((v: any) => v.meta.showLink)
  newTree.forEach((v: any) => v.children && (v.children = filterMenuTree(v.children)))
  return newTree
}
